import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { fakeAccountLogin, queryOemList } from '../services/api';
import { getAuthority } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';
import { getPageQuery } from '../utils/utils';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);

      // yield put({
      //   type: 'changeLoginStatus',
      //   payload: response,
      // });
      // Login successfull
      if (response) {
        if (response.status === 200) {
          localStorage.setItem('token', response.result.token);
          // 重新获取用户权限信息
          // const authRes = yield call(queryAuthResource);
          // setAuthority(authRes.result);
          // reloadAuthorized();

          const urlParams = new URL(window.location.href);
          const oemDataResponse = yield call(queryOemList);
          const list = oemDataResponse.result;
          const oemList = [];
          const oemMap = {};
          for (let i = 0; i < list.length; i++) {
            oemMap[list[i].id] = list[i].name;
            oemList.push({ value: list[i].id, label: list[i].name });
          }
          localStorage.setItem('oemData', JSON.stringify(oemList));
          localStorage.setItem('oemObj', JSON.stringify(oemMap));
          const params = getPageQuery();
          let { redirect } = params;
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.startsWith('/#')) {
                redirect = redirect.substr(2);
              }
            } else {
              window.location.href = redirect;
              return;
            }
          }
          yield put(routerRedux.replace(redirect || '/'));
        }
      } else {
        console.info('数据请求异常');
      }
    },
    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      // setAuthority(['merchant:merchant:save']);
      // reloadAuthorized();
      // 发出更新通知

      console.info('getAuthority', getAuthority());
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
